package cn.xej.health.team.service.impl;

import cn.xej.health.common.utils.CommonResult;
import cn.xej.health.team.dao.TeamDao;
import cn.xej.health.team.dao.TeamUserDao;
import cn.xej.health.team.entity.Team;
import cn.xej.health.team.entity.TeamUser;
import cn.xej.health.team.feign.UserFeignService;
import cn.xej.health.team.service.CaptainService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xej
 */
@Service
public class CaptainServiceImpl implements CaptainService {

    @Autowired
    private TeamDao teamDao;

    @Autowired
    private TeamUserDao teamUserDao;

    @Autowired
    private UserFeignService userFeignService;


    @Override
    public CommonResult queryMemberList(Integer uuid,Integer pageIndex, Integer pageSize, String searchName) {
        Team team = teamDao.selectOne(new QueryWrapper<Team>().eq("CAPTAIN_ID",uuid));
        CommonResult result = userFeignService.initMemberList(team.getTid(),pageIndex,pageSize,searchName);
        return CommonResult.success(result.getData());
    }

    @Override
    public void delete(List<Integer> uuidList) {
        teamUserDao.delete(new QueryWrapper<TeamUser>().in("uuid",uuidList));
    }


    @Override
    public CommonResult initRemainUserList() {
        CommonResult result = userFeignService.initRemainUserList();
        return CommonResult.success(result.getData());
    }


    @Override
    public CommonResult add(Integer captainId, Integer uuid) {
        Team team = teamDao.selectOne(new QueryWrapper<Team>().eq("CAPTAIN_ID",captainId));
        TeamUser teamUser = new TeamUser(team.getTid(),uuid);
        teamUserDao.insert(teamUser);
        return CommonResult.success(null);
    }


    @Override
    public CommonResult getTeamDockerList(Integer tid,Integer pageIndex,Integer pageSize) {
        Map<String,Object> map = new HashMap<>();
        int startNum = (pageIndex-1)*pageSize+1;
        int endNum = pageIndex*pageSize;

        List<TeamUser> teamUserList = teamUserDao.queryTeamUserList(startNum,endNum,tid);
        List<Integer> uuidList = new ArrayList<>();
        Team team = teamDao.selectById(tid);
        teamUserList.forEach((item)->{
            uuidList.add(item.getUuid());
        });
        uuidList.add(team.getCaptainId());
        // todo 将用户编号List 给 user 模块 去查询得到
        String json = JSONObject.toJSONString(uuidList);
        CommonResult result = userFeignService.getTeamDockerList(json);

        map.put("data",result.getData());
        map.put("total",uuidList.size());
        return CommonResult.success(map);
    }

}
